<?php

$auth = Auth::getAuth('current_user');
$db = new Database;
$fs = new functions();
$date = $fs->currentDateTime();

$formObject = new Form($db, $_GET["formId"]);
$search = $_GET["search"];
$condition = $_GET["condition"];

if(empty($condition)){ //DEFAULT VALUE OF CONDITION IF EMPTY ADDED BY MICHAEL
	$condition = "true";
}

$query = "SELECT * FROM " . $formObject->form_table_name;
$active_fields = split(",", $formObject->active_fields);
array_push($active_fields, "TrackNo");
if ($search != "") {
    $query .= " WHERE ";
    $count = 0;
    foreach ($active_fields as $field) {
        $count++;
        if (count($active_fields) == $count) {
            $query.= " " . $field . " LIKE '%" . $search . "%' ";
        } else {
            $query.= " " . $field . " LIKE '%" . $search . "%' OR ";
        }
    }
}

$requests = $db->query($query, "array");
$return_data = array();
if(!empty($condition)){
	foreach ($requests as $request) {
		$formulaObject = new Formula($condition);
		$formulaObject->setSourceForm($formObject->form_name, "*", array(
			array("FieldName" => "TrackNo",
				"Operator" => "=",
				"Value" => $request["TrackNo"]))
		);

		if ($formulaObject->evaluate() == "true") {
			array_push($return_data, $request);
		}
	}
	print_r(json_encode($return_data));
}else{
	print_r(json_encode($requests));
}



//print_r($query);
//
?>